﻿using Castle.Facilities.NHibernateIntegration;
using Castle.Core.Configuration;
using NHibernate.Cfg;
using System;
using NHibernate.Dialect;
using Inovout.Descriptors;

namespace Inovout.Repositories
{
    public class DatabaseConfigurationBuilder : IConfigurationBuilder
    {
        private const string connectionStringKey = "connectionString";
        private const string databaseTypeKey = "databaseType";

        public Configuration GetConfiguration(IConfiguration config)
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");// "NHibernate.Driver.SqlClientDriver";
            cfg.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");// "NHibernate.Driver.SqlClientDriver";
            cfg.SetProperty("connection.connection_string", config.Attributes[connectionStringKey]);// "ConnectionString
            cfg.SetProperty("dialect", GetDialect(config));// "ConnectionString
            //TODO：bytecode.provider
            //重写BytecodeProviderImpl.CreateInstance。通过IOC获取Domain。特别对于SAAS应用来说，尤其重要
            //cfg.SetProperty("proxyfactory.factory_class", typeof(ProxyFactoryFactory).FullName);
          //  cfg.SetProperty("default-lazy", "false");

          return cfg;
        }

        private string GetDialect(IConfiguration config)
        {
            EnumDescriptor databaseTypeDescriptor = new EnumDescriptor(typeof(DatabaseType));
            DatabaseType dataBaseType = (DatabaseType)databaseTypeDescriptor.GetEnum(config.Attributes[databaseTypeKey]);
            switch (dataBaseType)
            {
                case  DatabaseType.MsSql2008:
                    return typeof(MsSql2008Dialect).FullName;
                default:
                    throw new NotSupportedException();
            }
        }
    }
}
